package cn.heycm.cachedrequest.filter;

import cn.heycm.cachedrequest.entity.Result;
import cn.heycm.cachedrequest.filter.wrapper.CachedRequestWrapper;
import cn.heycm.cachedrequest.filter.wrapper.CachedResponseWrapper;
import cn.heycm.cachedrequest.util.Jackson;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@Slf4j
public class RequestLoggingFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (!(request instanceof CachedRequestWrapper requestWrapper) || !(response instanceof CachedResponseWrapper responseWrapper)) {
            filterChain.doFilter(request, response);
            return;
        }

        long start = System.currentTimeMillis();
        String method = requestWrapper.getMethod();
        String path = requestWrapper.getRequestURI();
        if ("GET".equalsIgnoreCase(method)) {
            String param = Jackson.toJson(requestWrapper.getParameterMap());
            log.info("## 请求: {} {} 参数: {}", method, path, param);
        } else {
            String param = Jackson.toJson(requestWrapper.getContentAsByteArray());
            log.info("## 请求: {} {} 参数: {}", method, path, param);
        }

        filterChain.doFilter(requestWrapper, responseWrapper);

        long end = System.currentTimeMillis();
        Result result = Jackson.toObject(responseWrapper.getContentAsByteArray(), Result.class);
        if (result != null) {
            log.info("## 请求: {} {} 响应: {} 耗时: {}ms", method, path, result.plain(), end - start);
        } else {
            log.info("## 请求: {} {} 耗时: {}ms", method, path, end - start);
        }
    }
}
